package com.zhou.springcloud.cousumer.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zhou.springcloud.api.pojo.Dept;
import com.zhou.springcloud.cousumer.service.IProdiverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zhouyongjun
 * @Description:
 * @date 2021/3/20 14:52
 */
@RestController
@RequestMapping("/consumer")
public class DeptCousumerController {
    @Autowired
    @Qualifier("restTemplate")
    RestTemplate restTemplate;
    //写死情况
//    static String REST_PROVIDER_URL_PREFIX="http://localhost:8001";
    //通过ribbon获取地址，通过服务名获取
    static String REST_PROVIDER_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT";
    @Autowired
    IProdiverService prodiverService;
    @RequestMapping("/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = restTemplate.getForObject(REST_PROVIDER_URL_PREFIX+"/dept/get/"+id,Dept.class);
        return dept;
    }

    @RequestMapping("/dept/add")
    public boolean addDept(Dept dept) {
        return restTemplate.postForObject(REST_PROVIDER_URL_PREFIX+"/dept/add",dept,Boolean.class);
    }
    @GetMapping("dept/list")
    public List<Dept> getAll() {
        try {
            String url = getUrl();
            List<Dept> list= restTemplate.getForObject(REST_PROVIDER_URL_PREFIX+"/dept/list",List.class);
            System.out.println(list);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    public String getUrl() {
        ServiceInstance serviceInstance = prodiverService.getServiceInstance("SPRINGCLOUD-PROVIDER-DEPT");
        return serviceInstance.getUri().toString();
    }
}
